// 引入外部资源
import { request } from "../../request/index";
import regeneratorRuntime from "../../libs/runtime";

Page({
  data: {
    tabs: [
      { id: 0, value: "综合", isActive: true },
      { id: 1, value: "销量", isActive: false },
      { id: 2, value: "价格", isActive: false },
    ],
    // 接口参数
    queryParams: {
      query: "",
      cid: "",
      pagenum: 1,
      pagesize: 10,
    },
    // 商品列表
    goodsList: [],
    // 总页数
    totalPage: 1,
  },
  // 组件点击事件
  handleTabsItemChange(e) {
    const { index } = e.detail;
    // 修改源数组
    let { tabs } = this.data;
    tabs.forEach((v, i) => {
      i === index ? (v.isActive = true) : (v.isActive = false);
    });
    // 重新赋值到 data 对象中
    this.setData({
      tabs,
    });
  },

  onLoad: function (options) {
    this.data.queryParams.cid = options.cid || "";
    this.data.queryParams.query = options.query || "";
    this.getGoodsList();
    wx.showLoading({
      title: "加载中",
    });

    setTimeout(function () {
      wx.hideLoading();
    }, 2000);
  },
  onReachBottom() {
    if (this.data.queryParams.pagenum >= this.totalPage) {
      // NOTE 微信提示弹框
      wx.showToast({
        title: "没有更多的数据了",
      });
    } else {
      this.data.queryParams.pagenum++;
      this.getGoodsList();
    }
  },
  onPullDownRefresh() {
    // 重置商品列表数组
    this.setData({
      goodsList: [],
    });
    // 重置页码
    this.data.queryParams.pagenum = 1;
    // 发送请求
    this.getGoodsList();
  },

  // 获取商品列表数据
  async getGoodsList() {
    const res = await request({ url: "/goods/search", data: this.queryParams });
    // 获取总页数并赋值
    this.totalPage = Math.ceil(
      res.data.message.total / this.data.queryParams.pagesize
    );

    // TODO异步数据对比: console.log(res.data.message);
    this.setData({
      // 拼接商品列表
      goodsList: [...this.data.goodsList, ...res.data.message.goods],
    });

    // TIPS 关闭下拉刷新窗口
    wx.stopPullDownRefresh();
  },
});
